//
//  NSString+TLQString.m
//  Tool
//
//  Created by BlueWind on 2017/10/20.
//  Copyright © 2017年 BlueWind. All rights reserved.
//

#import "NSString+TLQString.h"
#import <CommonCrypto/CommonDigest.h>
#import <CommonCrypto/CommonCryptor.h>
#import "sys/utsname.h"


@implementation NSString (TLQString)
const Byte iv[] = {1,2,3,4,5,6,7,8};


//生成用户的唯一ID
+(NSString *)UUID
{
    CFUUIDRef uuid_ref = CFUUIDCreate(NULL);
    CFStringRef uuid_string_ref= CFUUIDCreateString(NULL, uuid_ref);
    CFRelease(uuid_ref);
    NSString *uuid = [NSString stringWithString:(__bridge NSString*)uuid_string_ref];
    CFRelease(uuid_string_ref);
    return uuid;
}

- (NSString *)md5
{
    const char *cStr = [self UTF8String];
    unsigned char result[16];
    CC_MD5( cStr, (unsigned int) strlen(cStr), result);
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}


- (NSString*)sha1

{
    
    const char *cstr = [self cStringUsingEncoding:NSUTF8StringEncoding];
    
    NSData *data = [NSData dataWithBytes:cstr length:self.length];
    uint8_t digest[CC_SHA1_DIGEST_LENGTH];
    CC_SHA1(data.bytes, (uint32_t)data.length, digest);
    NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
    
    for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++)
        [output appendFormat:@"%02x", digest[i]];
    
    
    
    return output;
    
}

-(NSString*)encode {
    
    // CharactersToBeEscaped = @":/?&=;+!@#$()~',*";
    // CharactersToLeaveUnescaped = @"[].";
    
    NSString *encodedString = [self stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    return encodedString;
}

//URLDEcode
-(NSString *)decode {
    
    NSString *decodedString = [self stringByRemovingPercentEncoding];
    
    return decodedString;
}



-(NSDate *)dateValue {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    return [dateFormatter dateFromString:self];
}

-(NSURL *)URLValue {
    return [NSURL URLWithString:self];
}



/**
 验证是否为邮箱格式
 
 @param email 传入的字符串
 @return 是否为邮箱 YES 为邮箱格式 No 不是邮箱格式
 */
+ (BOOL)validateEmail:(NSString *)email {
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}


- (BOOL)validateByRegex:(NSString *)regex {
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    return [phoneTest evaluateWithObject:self];
}


- (BOOL)validateMobile {
    NSString *MOBIL = @"^1([3-9])\\d{9}$";
    return [self validateByRegex:MOBIL];
}

//车牌号验证
- (BOOL)validateCarNo:(NSString *)carNo
{
    NSString *carRegex = @"^[\u4e00-\u9fa5]{1}[a-zA-Z]{1}[a-zA-Z_0-9]{4}[a-zA-Z_0-9_\u4e00-\u9fa5]$";
    return [self validateByRegex:carRegex];
}


//车型
- (BOOL)validateCarType:(NSString *)CarType
{
    NSString *CarTypeRegex = @"^[\u4E00-\u9FFF]+$";
    NSPredicate *carTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",CarTypeRegex];
    return [carTest evaluateWithObject:CarType];
}



/**
 用户昵称验证
 
 @param name 传入的字符串
 @return  YES 是 NO 不是
 */
+ (BOOL)validateUserName:(NSString *)name
{
    NSString *userNameRegex = @"^[0-9A-Za-z\u4e00-\u9fa5]{2,20}$";
    NSPredicate *userNamePredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",userNameRegex];
    BOOL B = [userNamePredicate evaluateWithObject:name];
    return B;
}


//密码
+ (BOOL)validatePassword:(NSString *)passWord
{
    
    
//    ^(?=.*[a-zA-Z0-9].*)(?=.*[a-zA-Z\\W].*)(?=.*[0-9\\W].*).{6,20}$
    NSString *passWordRegex = @"^(?=.*[a-zA-Z0-9].*)(?=.*[a-zA-Z\\W].*)(?=.*[0-9\\W].*).{6,18}$";
    NSPredicate *passWordPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",passWordRegex];
    return [passWordPredicate evaluateWithObject:passWord];
}


//身份证号
+ (BOOL)validateIdentityCard: (NSString *)identityCard
{
    identityCard = [identityCard stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    NSInteger length =0;
    if (!identityCard) {
        return NO;
    }else {
        length = identityCard.length;
        //不满足15位和18位，即身份证错误
        if (length !=15 && length !=18) {
            return NO;
        }
    }
    // 省份代码
    NSArray *areasArray = @[@"11",@"12", @"13",@"14", @"15",@"21", @"22",@"23", @"31",@"32", @"33",@"34", @"35",@"36", @"37",@"41", @"42",@"43", @"44",@"45", @"46",@"50", @"51",@"52", @"53",@"54", @"61",@"62", @"63",@"64", @"65",@"71", @"81",@"82", @"91"];
    
    // 检测省份身份行政区代码
    NSString *valueStart2 = [identityCard substringToIndex:2];
    BOOL areaFlag =NO; //标识省份代码是否正确
    for (NSString *areaCode in areasArray) {
        if ([areaCode isEqualToString:valueStart2]) {
            areaFlag =YES;
            break;
        }
    }
    
    if (!areaFlag) {
        return NO;
    }
    
    NSRegularExpression *regularExpression;
    NSUInteger numberofMatch;
    
    int year =0;
    //分为15位、18位身份证进行校验
    switch (length) {
        case 15:
            //获取年份对应的数字
            year = [identityCard substringWithRange:NSMakeRange(6,2)].intValue +1900;
            
            if (year %4 ==0 || (year %100 ==0 && year %4 ==0)) {
                //创建正则表达式 NSRegularExpressionCaseInsensitive：不区分字母大小写的模式
                regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}$"
                                                                        options:NSRegularExpressionCaseInsensitive error:nil];//测试出生日期的合法性
            }else {
                regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}$"
                                                                        options:NSRegularExpressionCaseInsensitive error:nil];//测试出生日期的合法性
            }
            //使用正则表达式匹配字符串 NSMatchingReportProgress:找到最长的匹配字符串后调用block回调
            numberofMatch = [regularExpression numberOfMatchesInString:identityCard
                                                               options:NSMatchingReportProgress
                                                                 range:NSMakeRange(0, identityCard.length)];
            
            if(numberofMatch >0) {
                return YES;
            }else {
                return NO;
            }
        case 18:
            year = [identityCard substringWithRange:NSMakeRange(6,4)].intValue;
            if (year %4 ==0 || (year %100 ==0 && year %4 ==0)) {
                regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}[0-9Xx]$" options:NSRegularExpressionCaseInsensitive error:nil];//测试出生日期的合法性
            }else {
                regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}[0-9Xx]$" options:NSRegularExpressionCaseInsensitive error:nil];//测试出生日期的合法性
            }
            numberofMatch = [regularExpression numberOfMatchesInString:identityCard
                                                               options:NSMatchingReportProgress
                                                                 range:NSMakeRange(0, identityCard.length)];
            
            
            if(numberofMatch >0) {
                //1：校验码的计算方法 身份证号码17位数分别乘以不同的系数。从第一位到第十七位的系数分别为：7－9－10－5－8－4－2－1－6－3－7－9－10－5－8－4－2。将这17位数字和系数相乘的结果相加。
                
                int S = [identityCard substringWithRange:NSMakeRange(0,1)].intValue*7 + [identityCard substringWithRange:NSMakeRange(10,1)].intValue *7 + [identityCard substringWithRange:NSMakeRange(1,1)].intValue*9 + [identityCard substringWithRange:NSMakeRange(11,1)].intValue *9 + [identityCard substringWithRange:NSMakeRange(2,1)].intValue*10 + [identityCard substringWithRange:NSMakeRange(12,1)].intValue *10 + [identityCard substringWithRange:NSMakeRange(3,1)].intValue*5 + [identityCard substringWithRange:NSMakeRange(13,1)].intValue *5 + [identityCard substringWithRange:NSMakeRange(4,1)].intValue*8 + [identityCard substringWithRange:NSMakeRange(14,1)].intValue *8 + [identityCard substringWithRange:NSMakeRange(5,1)].intValue*4 + [identityCard substringWithRange:NSMakeRange(15,1)].intValue *4 + [identityCard substringWithRange:NSMakeRange(6,1)].intValue*2 + [identityCard substringWithRange:NSMakeRange(16,1)].intValue *2 + [identityCard substringWithRange:NSMakeRange(7,1)].intValue *1 + [identityCard substringWithRange:NSMakeRange(8,1)].intValue *6 + [identityCard substringWithRange:NSMakeRange(9,1)].intValue *3;
                
                //2：用加出来和除以11，看余数是多少？余数只可能有0－1－2－3－4－5－6－7－8－9－10这11个数字
                int Y = S %11;
                NSString *M =@"F";
                NSString *JYM =@"10X98765432";
                M = [JYM substringWithRange:NSMakeRange(Y,1)];// 3：获取校验位
                //4：检测ID的校验位
                if ([M isEqualToString:[identityCard substringWithRange:NSMakeRange(17,1)]]) {
                    return YES;
                }else {
                    return NO;
                }
                
            }else {
                return NO;
            }
        default:
            return NO;
    }
}

// 计算字符串高度
- (CGFloat)heigthWithWeight:(CGFloat)weight andFont:(CGFloat)font andLineSpacing:(NSInteger )lineSpacing andWordSpacing:(CGFloat )wordSpacing{
    NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
    paraStyle.lineSpacing = lineSpacing; //设置行间距
    //设置字间距 NSKernAttributeName:@1.5f
    NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:font], NSParagraphStyleAttributeName:paraStyle, NSKernAttributeName:@(wordSpacing)
                          };
    
    //    NSDictionary *attribute = @{NSFontAttributeName: [UIFont systemFontOfSize:font]};
    CGSize size = [self boundingRectWithSize:CGSizeMake(weight, MAXFLOAT)
                                     options:(NSStringDrawingUsesFontLeading|NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesLineFragmentOrigin)
                                  attributes:dic
                                     context:nil].size;
    return size.height;
    
}


/** * 计算字符串宽度 * * @param height 字符串的高度 * @param font 字体大小 * * @return 字符串的尺寸 */
- (CGFloat)widthWithHeight:(CGFloat)height andFont:(CGFloat)font {
    NSDictionary *attribute = @{NSFontAttributeName: [UIFont systemFontOfSize:font]};
    CGSize size = [self boundingRectWithSize:CGSizeMake(MAXFLOAT, height)
                                     options:(NSStringDrawingUsesFontLeading|NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesLineFragmentOrigin)
                                  attributes:attribute
                                     context:nil].size;
    return size.width;
}


- (CGFloat)font:(NSInteger)font {
    
    CGFloat f = [UIFont systemFontOfSize:font].lineHeight;
    
    return f;
}

// 字典转化为 JSON 字符串
+ (NSString *)JSONWithDictionary:(NSDictionary *)dictionary {
    NSError *error = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:&error];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}





-(NSArray *)arrayDividedByString:(NSString *)separator {
    return [self componentsSeparatedByString:separator];
}

- (NSArray *)arrayDividedByString:(NSString *)separator withBlock:(id (^)(id obj))block {
    NSParameterAssert(block != nil);
    
    NSMutableArray *result = [NSMutableArray new];
    
    [[self componentsSeparatedByString:separator] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        id value = block(obj)?:[NSNull null];
        [result addObject:value];
    }];
    
    return result;
}

+(NSString*)stringFromParamsDict:(NSDictionary*)params
{
    NSMutableArray* array = [@[]mutableCopy];
    [params enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        NSString* string = [NSString stringWithFormat:@"%@=%@",key,obj];
        [array addObject:string];
    }];
    return [array componentsJoinedByString:@"&"];
}

+ (NSString*)deviceVersion
{
    // 需要#import "sys/utsname.h"
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString * deviceString = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
    //iPhone
    
    if ([deviceString isEqualToString:@"iPhone3,1"])    return @"iPhone 4";
    if ([deviceString isEqualToString:@"iPhone3,2"])    return @"Verizon iPhone 4";
    if ([deviceString isEqualToString:@"iPhone4,1"])    return @"iPhone 4S";
    if ([deviceString isEqualToString:@"iPhone5,1"])    return @"iPhone 5";
    if ([deviceString isEqualToString:@"iPhone5,2"])    return @"iPhone 5";
    if ([deviceString isEqualToString:@"iPhone5,3"])    return @"iPhone 5C";
    if ([deviceString isEqualToString:@"iPhone5,4"])    return @"iPhone 5C";
    if ([deviceString isEqualToString:@"iPhone6,1"])    return @"iPhone 5S";
    if ([deviceString isEqualToString:@"iPhone6,2"])    return @"iPhone 5S";
    if ([deviceString isEqualToString:@"iPhone7,1"])    return @"iPhone 6 Plus";
    if ([deviceString isEqualToString:@"iPhone7,2"])    return @"iPhone 6";
    if ([deviceString isEqualToString:@"iPhone8,1"])    return @"iPhone 6s";
    if ([deviceString isEqualToString:@"iPhone8,2"])    return @"iPhone 6s Plus";
    if ([deviceString isEqualToString:@"iPhone8,4"])    return @"iPhone SE";
    if ([deviceString isEqualToString:@"iPhone9,1"])    return @"iPhone 7";
    if ([deviceString isEqualToString:@"iPhone9,2"])    return @"iPhone 7 Plus";
    if ([deviceString isEqualToString:@"iPhone10,1"])   return @"iPhone 8";
    if ([deviceString isEqualToString:@"iPhone10,4"])   return @"iPhone 8";
    if ([deviceString isEqualToString:@"iPhone10,2"])   return @"iPhone 8 Plus";
    if ([deviceString isEqualToString:@"iPhone10,5"])   return @"iPhone 8 Plus";
    if ([deviceString isEqualToString:@"iPhone10,3"])   return @"iPhone X";
    if ([deviceString isEqualToString:@"iPhone10,6"])   return @"iPhone X";
    
    return deviceString;
}

+ (NSString *)returen:(NSInteger)status {
    if (status == 1001) {
        return @"参数错误";
    } else if (status == 1002) {
        return @"token 无效";
    } else if (status == 1003) {
        return @"登录设备数量超过限制";
    } else if (status == 1004) {
        return @"插入信息中包含的外键值不合法，无法确定从属关系";
    } else if (status == 1005) {
        return @"操作的数据不属于当前用户";
    } else if (status == 1006) {
        return @"错误的枚举值";
    } else if (status == 1007) {
        return @"手机号码已存在";
    } else if (status == 1008) {
        return @"手机号不合法";
    } else if (status == 1009) {
        return @"验证码错误";
    } else if (status == 1010) {
        return @"手机号码未注册";
    } else if (status == 1011) {
        return @"头像大小超过限制";
    } else if (status == 1012) {
        return @"图片大小超过限制";
    } else if (status == 1013) {
        return @"第三方平台ID已存在";
    } else if (status == 1014) {
        return @"第三方平台ID不存在";
    } else if (status == 1015) {
        return @"金币数量不足";
    } else if (status == 1016) {
        return @"图片不存在";
    } else if (status == 1017) {
        return @"鉴权失败";
    } else if (status == 1018) {
        return @"重复请求";
    } else if (status == 1019) {
        return @"昵称已存在";
    } else if (status == 1020) {
        return @"第三方登录的access_token 和 openid 校验失败";
    } else {
        return @"未知错误";
    }
}

// 计算字符串大小
- (CGSize)contentSizeWithWidth:(CGFloat)width
                          font:(UIFont *)font
                   lineSpacing:(CGFloat)lineSpacing {
    if (self == nil || [self length] <= 0) {
        return CGSizeMake(0, 0);
    }
    NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:self];
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    style.lineSpacing = lineSpacing;
    [attributeString addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0, self.length)];
    [attributeString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, self.length)];
    NSStringDrawingOptions options = NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading;
    CGRect rect = [attributeString boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX) options:options context:nil];
    
    //文本的高度减去字体高度小于等于行间距，判断为当前只有1行
    if ((rect.size.height - font.lineHeight) <= style.lineSpacing) {
        if ([self containChinese:self]) {
            rect = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height-style.lineSpacing);
        }
    }
    //return ceil(rect.size.height);
    return rect.size;
}

// 是否只有一行
- (BOOL)contentHaveOneLinesWithWidth:(CGFloat)width
                                font:(UIFont *)font
                         lineSpacing:(CGFloat)lineSpacing {
    NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:self];
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    style.lineSpacing = lineSpacing;
    [attributeString addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0, self.length)];
    [attributeString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, self.length)];
    NSStringDrawingOptions options = NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading;
    CGRect rect = [attributeString boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX) options:options context:nil];
    //文本的高度减去字体高度小于等于行间距，判断为当前只有1行
    if ((rect.size.height - font.lineHeight) <= style.lineSpacing) {
        return YES;
    } else {
        return NO;
    }
}

//判断是否包含中文
- (BOOL)containChinese:(NSString *)str {
    for(int i=0; i< [str length];i++){
        int a = [str characterAtIndex:i];
        if( a > 0x4e00 && a < 0x9fff){
            return YES;
        }
    }
    return NO;
}

/**
 字符串竖着显示
 
 @return 竖着的字符串
 */
- (NSString *)VerticalString{
    NSMutableString * str = [[NSMutableString alloc] initWithString:self];
    NSInteger count = str.length;
    for (int i = 1; i < count; i ++) {
        [str insertString:@"\n" atIndex:i*2 - 1];
    }
    return str;
}

/**
 显示身份证 加密
 
 @param idCard 身份证号码
 @return 加密身份证号
 */
+ (NSString *)encryptIdentityCard:(NSString *)idCard{
    if(idCard.length!=18){
        return idCard;
    }
    NSString *strheard = [idCard substringWithRange:NSMakeRange(0, 1)];
    NSString *strfoot   = [idCard substringWithRange:NSMakeRange(idCard.length-1, 1)];
    NSString *Newphone = [NSString stringWithFormat:@"%@****************%@",strheard,strfoot];
    return Newphone;
}

/**
 字符串开始插入图片
 
 @param imageName 图片名
 @param content 字符串内容
 @return 返回富文本
 */
+ (NSMutableAttributedString *)insertImage:(NSString *)imageName content:(NSString *)content imageSize:(CGRect)frame{
    
    // 创建一个富文本
    NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithString:content];
    NSTextAttachment *attch = [[NSTextAttachment alloc] init];
    // 表情图片
    attch.image = [UIImage imageNamed:imageName];
    // 设置图片大小
    attch.bounds = frame;
    // 创建带有图片的富文本
    NSAttributedString *string = [NSAttributedString attributedStringWithAttachment:attch];
    //    [attri appendAttributedString:string]; //在文字后面添加图片
    // 在文字下标第几个添加图片  0就是文字前面添加图片
    [attri insertAttributedString:string atIndex:0];
    return attri;
}

+ (NSString *)initWithNum:(NSInteger)num {
    
    NSString *str = @"";
    if (num >= 10000) {
        str = [NSString stringWithFormat:@"%0.1fw",num/10000.0];
    } else {
        str = [NSString stringWithFormat:@"%ld",num];
    }
    return str;
}


@end

